import i18n from '@/i18nWidget/index'
const defaultTranslations = Object.fromEntries(
  Object.entries(i18n).filter(([key]) => key.includes('en'))
).en

export const standardFieldKeys = {
  emailAddress: {
    key: 'EMAIL_ADDRESS',
    label: 'Email Id',
    placeholder: 'Please enter your email address',
  },
  fullName: {
    key: 'FULL_NAME',
    label: 'Full Name',
    placeholder: 'Please enter your full name',
  },
  phoneNumber: {
    key: 'PHONE_NUMBER',
    label: 'Phone Number',
    placeholder: 'Please enter your phone number',
  },
}

export const getLabel = ({ key, label }) => {
  return defaultTranslations.PRE_CHAT_FORM.FIELDS[key]
    ? defaultTranslations.PRE_CHAT_FORM.FIELDS[key].LABEL
    : label
}
export const getPlaceHolder = ({ key, placeholder }) => {
  return defaultTranslations.PRE_CHAT_FORM.FIELDS[key]
    ? defaultTranslations.PRE_CHAT_FORM.FIELDS[key].PLACEHOLDER
    : placeholder
}

export const getCustomFields = ({ standardFields, customAttributes }) => {
  const customFields = []
  const { preChatFields: preChatFields } = standardFields
  customAttributes.forEach(attribute => {
    const itemExist = preChatFields.find(
      item => item.name === attribute.attributeKey
    )
    if (!itemExist) {
      customFields.push({
        label: attribute.attributeDisplayName,
        placeholder: attribute.attributeDisplayName,
        name: attribute.attributeKey,
        type: attribute.attributeDisplayType,
        values: attribute.attributeValues,
        fieldType: attribute.attributeModel,
        required: false,
        enabled: false,
      })
    }
  })
  return customFields
}

export const getFormattedPreChatFields = ({ preChatFields }) => {
  return preChatFields.map(item => {
    return {
      ...item,
      label: getLabel({
        key: item.name,
        label: item.label ? item.label : item.name,
      }),
      placeholder: getPlaceHolder({
        key: item.name,
        placeholder: item.placeholder ? item.placeholder : item.name,
      }),
    }
  })
}

export const getPreChatFields = ({
  preChatFormOptions = {},
  customAttributes = [],
}) => {
  const { preChatMessage, preChatFields } = preChatFormOptions
  let customFields = {}
  let preChatFieldsAll = {}

  const formattedPreChatFields = getFormattedPreChatFields({
    preChatFields: preChatFields,
  })

  customFields = getCustomFields({
    standardFields: { preChatFields: formattedPreChatFields },
    customAttributes,
  })
  preChatFieldsAll = [...formattedPreChatFields, ...customFields]

  return {
    preChatMessage,
    preChatFields: preChatFieldsAll,
  }
}
